//
//  HXDEmoticonTools.swift
//  weibo
//
//  Created by huxuedong on 15/12/15.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

let kRowsOfPage = 3
let kColumnsOfPage = 7
let kEmoticonNumOfPage = kRowsOfPage * kColumnsOfPage - 1

class HXDEmoticonTools: NSObject {
    
    static let sharedInstance: HXDEmoticonTools = HXDEmoticonTools()
    
    lazy var emoticonBundel: NSBundle = {
        //获取bundle文件路径
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        return NSBundle(path: path)!
    }()
    private lazy var recentEmoticons: [HXDEmoticon] = {
        var emoticon = NSKeyedUnarchiver.unarchiveObjectWithFile(self.recentEmoticonPath) as? [HXDEmoticon]
        if emoticon == nil {
            emoticon = [HXDEmoticon]()
        }
        return emoticon!
    }()
    private lazy var defaultEmoticon: [HXDEmoticon] = {
        return self.getEmoticonWithPath("default/info.plist")
    }()
    private lazy var emojiEmoticons: [HXDEmoticon] = {
        return self.getEmoticonWithPath("emoji/info.plist")
    }()
    private lazy var lxhEmoticons: [HXDEmoticon] = {
        return self.getEmoticonWithPath("lxh/info.plist")
    }()
    lazy var allEmoticons: [[[HXDEmoticon]]] = {
        return [
            self.sectionDataWithEmoticons(self.recentEmoticons),
            self.sectionDataWithEmoticons(self.defaultEmoticon),
            self.sectionDataWithEmoticons(self.emojiEmoticons),
            self.sectionDataWithEmoticons(self.lxhEmoticons)
        ]
    }()
    private lazy var recentEmoticonPath: String = {
        //将最近表情保存到沙盒的Document文件夹下
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmoticon.data")
        return path
    }()
    
    //通过表情字符串获取表情
    func getEmoticonWithChs(chs: String) -> HXDEmoticon? {
        //定义谓词搜索条件
        let predicate = NSPredicate(format: "chs == %@", chs)
        //先查找默认表情
        var result = (defaultEmoticon as NSArray).filteredArrayUsingPredicate(predicate)
        if let first = result.first as? HXDEmoticon {
            return first
        }
        //默认表情没查找到再查找浪小花表情
        result = (lxhEmoticons as NSArray).filteredArrayUsingPredicate(predicate)
        if let first = result.first as? HXDEmoticon {
            return first
        }
        //都没查找到
        return nil
    }
    
    //通过文件路径读取表情图片名称
    private func getEmoticonWithPath(path: String) -> [HXDEmoticon] {
        //获取plist文件路径
        let fullPath = self.emoticonBundel.pathForResource(path, ofType: nil)!
        //将文件数据写入数组中
        let array = NSArray(contentsOfFile: fullPath)!
        //实例化模型数组
        var data = [HXDEmoticon]()
        for value in array {
            //如果是字典，则将数据转化为模型并添加到模型数组中
            if let dict = value as? [String: AnyObject] {
                let model = HXDEmoticon(dict: dict)
                //获取不包含文件名的路径
                model.path = (path as NSString).stringByDeletingLastPathComponent
                data.append(model)
            }
        }
        return data
    }
    
    //根据不同类型的表情获取每组的数据
    private func sectionDataWithEmoticons(emoticons: [HXDEmoticon]) -> [[HXDEmoticon]] {
        //获取每个类型的表情的显示页数
        let pageCount = (emoticons.count - 1) / kEmoticonNumOfPage + 1
        var data = [[HXDEmoticon]]()
        for i in 0..<pageCount {
            //截取的开始位置
            let start = i * kEmoticonNumOfPage
            //截取的长度
            var length = kEmoticonNumOfPage
            //如果剩下的表情不够20
            if start + length > emoticons.count {
                //截取的长度 = 表情的个数 - 开始的位置
                length = emoticons.count - start
            }
            let range = NSMakeRange(start, length)
            //截取数组
            let subArray = (emoticons as NSArray).subarrayWithRange(range) as! [HXDEmoticon]
            data.append(subArray)
        }
        return data
    }
    
    func saveRecentEmoticon(emoticon: HXDEmoticon) {
        let array = recentEmoticons as NSArray
        //获取表在数组中的位置
        let index = array.indexOfObject(emoticon)
        //如果在数组中找到了
        if index != NSNotFound {
            //移除对应位置的表情
            recentEmoticons.removeAtIndex(index)
        }
        //在位置0插入表情
        recentEmoticons.insert(emoticon, atIndex: 0)
        //如果数组长度超过20
        while recentEmoticons.count > 20 {
            //移除数组的最后一个元素
            recentEmoticons.removeLast()
        }
        //设置第0组第0页显示最近表情
        allEmoticons[0][0] = recentEmoticons
        //归档
        NSKeyedArchiver.archiveRootObject(recentEmoticons, toFile: recentEmoticonPath)
    }

}
